package com.chj.comp.service.demo1.service.impl;

import com.chj.comp.common.core.util.Result;
import com.chj.comp.common.es.constant.CommandConstant;
import com.chj.comp.common.es.constant.IndexConstant;
import com.chj.comp.common.es.document.AccessLogDocument;
import com.chj.comp.common.es.document.PersonDataDocument;
import com.chj.comp.service.demo1.service.IEsTestService;
import lombok.extern.slf4j.Slf4j;
import org.frameworkset.elasticsearch.boot.BBossESStarter;
import org.frameworkset.elasticsearch.client.ClientInterface;
import org.frameworkset.elasticsearch.entity.ESDatas;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ：cuihui
 * @date ：Created in 2022/4/17
 * @description：es接口示例
 * @modified By：
 */
@Service
@Slf4j
public class EsTestService implements IEsTestService {

    @Autowired
    private BBossESStarter bbossESStarter;

    @Override
    public void saveAccessLog(AccessLogDocument accessLogDocument) {
        ClientInterface clientUtil = bbossESStarter.getConfigRestClient("esmapper/AccessLogMapper.xml");
        /** 按月份动态产生索引名（需提前建立索引模板） */
        clientUtil.addDateDocument(IndexConstant.INDEX_NAME_ACCESS_LOG, accessLogDocument);
    }

    @Override
    public Result<AccessLogDocument> getAccessLogById(String id){
        ClientInterface clientUtil = bbossESStarter.getConfigRestClient("esmapper/AccessLogMapper.xml");
        Map param = new HashMap();
        param.put("id", id);
        ESDatas<AccessLogDocument> esDatas = clientUtil
                .searchList(IndexConstant.INDEX_NAME_ACCESS_LOG.concat(CommandConstant.separator).concat(CommandConstant.search),
                        "getAccessLogById",
                        param,
                        AccessLogDocument.class);
        List<AccessLogDocument> list = esDatas.getDatas();
        return Result.ok(list.get(0));
    }

    @Override
    public void savePersonData(PersonDataDocument personDataDocument) {
        ClientInterface clientUtil = bbossESStarter.getConfigRestClient("esmapper/PersonDataMapper.xml");
        /** 保存数据（需提前建立索引） */
        clientUtil.addDocument(IndexConstant.INDEX_NAME_PERSON_DATA, personDataDocument);
    }
}
